package com.xb.ai.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.xb.ai.annotation.Login;
import com.xb.ai.common.PageResponse;
import com.xb.ai.common.PageRequest;
import com.xb.ai.common.Result;
import com.xb.ai.constant.ErrorMessage;
import com.xb.ai.entity.po.Webpage;
import com.xb.ai.entity.vo.WebpagePage;
import com.xb.ai.entity.vo.WebpageVo;
import com.xb.ai.exception.BusinessException;
import com.xb.ai.service.IWebpageService;

import jakarta.annotation.Resource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/webpage")
public class WebPageController {

    @Resource
    private IWebpageService webpageService;

    /**
     * 获取网页列表
     * @return 网页信息
     */
    @GetMapping("/list")
    public Result<PageResponse<WebpagePage>> getWebPageList(PageRequest pageRequest) {
        return Result.success(webpageService.getWebPageList(pageRequest));
    }

    /**
     * 获取网页信息
     * @param id 网页id
     * @return 网页信息
     */
    @GetMapping("/get")
    public Result<WebpageVo> getWebPage(Long id) {
        if (id == null) {
            throw new BusinessException(ErrorMessage.PARAMS_ERROR);
        }
        Webpage webpage = webpageService.getById(id);
        return Result.success(BeanUtil.copyProperties(webpage, WebpageVo.class));
    }


    /**
     * 下载网页
     * @param id 网页id
     * @return 网页信息
     */
    @Login
    @GetMapping("/download/{id}")
    public ResponseEntity<org.springframework.core.io.Resource> downloadWebpage(@PathVariable("id") Long id){
        if (id == null) {
            throw new BusinessException(ErrorMessage.PARAMS_ERROR);
        }
        if (!StpUtil.isLogin()) {
            throw new BusinessException(ErrorMessage.NOT_LOGIN_ERROR);
        }
        File zipFile = webpageService.getWebpageZipFile(id);

        // 从服务获取文件名
        String fileName = webpageService.getById(id).getWebpageTitle();
        // 确保文件名以.zip结尾
        if (!fileName.toLowerCase().endsWith(".zip")) {
            fileName = fileName + ".zip";
        }
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8)
                .replace("+", "%20");
        // 创建文件资源
        FileSystemResource resource = new FileSystemResource(zipFile);
        // 设置HTTP头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFileName + "\"; filename*=UTF-8''" + encodedFileName);
        // 返回文件
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(zipFile.length())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }


}
